import React, {Component} from 'react';
import {StyleSheet, Text, View,Button ,TextInput,
  Alert,
  TouchableOpacity,
} from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast'
import TopBar from '../bar/TopBar';
import Picker from 'react-native-picker';
import SQLite from '../db/sqlite';
import {getCurrentDate,createDateData} from '../common/common'
const dismissKeyboard = require('dismissKeyboard');
const ACCOUNT_TABLE = "t_account";//用户表
var sqLitec = new SQLite();
var db;
export default class AddAccount extends Component{
  static navigationOptions = ({ navigation }) =>{
    return{
      headerTitle:<TopBar title='新增' navigation = {navigation} />,
      headerLeft:null,
    }
  };
  constructor(props){
    super(props);
    this.state=({
      id:this.props.navigation.getParam('id'),
      val1:'5', //成本
      val2:'10', // 单价
      val3:'', //宽粉 重量
      val4:'',  //宽粉 金额
      val5:'',  //细粉 重量
      val6:'',  //细粉  金额
      val7:'0',  //赠送 重量
      totalFund:'0',
      totalCost:'0',
      totalIncome:'0',
      val8:'0',
      time:getCurrentDate(),
      account:{}
    })
  }
  componentWillMount(){
    if(this.state.id){
      this._getDetail();
    }
  }
  componentDidMount(){
  }
  _selectDate(){
    var year = '';
    var month = '';
    var day = '';
    var dateStr = this.state.time;
    year = dateStr.substring(0,4)
    month = parseInt(dateStr.substring(5,7))
    day = parseInt(dateStr.substring(8,10))
    Picker.init({
      pickerTitleText:'日期选择',
      pickerCancelBtnText:'取消',
      pickerConfirmBtnText:'确定',
      selectedValue:[year+'年',month+'月',day+'日'],
      pickerBg:[255,255,255,1],
      pickerData: createDateData(),
      pickerFontColor: [33, 33 ,33, 1],
      onPickerConfirm: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
          var year = pickedValue[0].substring(0,pickedValue[0].length-1)
          var month = pickedValue[1].substring(0,pickedValue[1].length-1)
          month = month.padStart(2,'0')
          var day = pickedValue[2].substring(0,pickedValue[2].length-1)
          day = day.padStart(2,'0')
          let str = year+'-'+month+'-'+day
          this.setState({
            time:str,
          })  
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
          //console.log('date', pickedValue, pickedIndex);
      }
    });
    Picker.show();
  }
  _getDetail(){
    if(!db){
      db = sqLitec.open();
    }
    db.transaction((tx)=>{
      var id = this.state.id;
      if(id){//更新
        note_id = id;
        let sql = "select * from  "+ACCOUNT_TABLE+" where id=?";
        tx.executeSql(sql,[id],(tx,results)=>{
          //console.log("--detail--result",results);
          var account = results.rows.item(0);
          console.log('acc',account);
          this.setState({
            val1: account.val1, //成本
            val2: account.val2, // 单价
            val3: account.val3, //宽粉 重量
            val4: account.val4,  //宽粉 金额
            val5: account.val5,  //细粉 重量
            val6: account.val6,  //细粉  金额
            val7: account.val7,  //赠送 重量
            totalFund: account.total_fund,
            totalCost: account.total_cost,
            totalIncome: account.total_income,
            val8: account.val8,
            time: account.create_time
          })
        },(err)=>{

        });
      } 
      
    },(error)=>{
      console.log(error);
    },()=>{

      
    });
  }
  _save(){
    dismissKeyboard();
    let {totalFund,totalCost,totalIncome} = this.state;
    if(totalFund == '0' || totalCost == '0' || totalIncome =='0'){
      this.refs.toast.show('请填写完整的信息');
      return;
    }
    Alert.alert(
      '提示',
      '您确定要保存吗？',
      [
        {text:'取消',onPress:()=>{
        
        }},
        {text:'确定',onPress:()=>{
          this._saveData();
        }},
      ],
   );
  }
  _saveData(){
    var {val1,val2,val3,val4,val5,val6,val7,val8,totalFund,totalCost,totalIncome,time} = this.state;
    val5 = val5?val5:0;
    if(!db){
      db = sqLitec.open();
    }
    db.transaction((tx)=>{
      var id = this.state.id ;
      if(id){//更新
        let sql = "update "+ACCOUNT_TABLE+" set val1=?,val2=?,val3=?,val4=?,val5=?,val6=?,val7=?,val8=?,"
              +"total_fund=?,total_cost=?,total_income=?,create_time=? where id=?";
        tx.executeSql(sql,[val1,val2,val3,val4,val5,val6,val7,val8,totalFund,totalCost,totalIncome,time,id],(tx,results)=>{
          //console.log("--update--result");
          this.refs.toast.show('保存成功');
          setTimeout(()=>{
            this.props.navigation.pop();
          },2000)
        },(err)=>{

        });
      } else {
        let sql = "insert into "+ACCOUNT_TABLE+"(val1,val2,val3,val4,val5,val6,val7,val8,total_fund,total_cost,"
          +" total_income,create_time) values(?,?,?,?,?,?,?,?,?,?,?,?)";
        tx.executeSql(sql,[val1,val2,val3,val4,val5,val6,val7,val8,totalFund,totalCost,totalIncome,time],(tx,results)=>{
          //console.log("--insert--result");
          //console.log('insert id',results.insertId);
          this.refs.toast.show('保存成功');
          const {goBack,state} = this.props.navigation;
          const {navigation} = this.props;
          console.log('navigation',this.props.navigation)
          setTimeout(()=>{
            //this.props.navigation.pop();
            state.params.callback('');
            navigation.goBack(); 
          },1500)
        },(err)=>{

        });
      }
      
    },(error)=>{
      console.log(error);
    },()=>{

      
    });
  }
  _onchange(val,type){
    //val = val?val:'0'
    if('val1' == type){
      this.setState({
        val1:val,
      })
    } else if('val2' == type){
      this.setState({
        val2:val,
        val4:parseFloat(this.state.val3)*parseFloat(val?val:'0')+'',
        val6:parseFloat(this.state.val6)*parseFloat(val?val:'0')+''
      })
    } else if('val3' == type){
      this.setState({
        val3:val,
        val4:parseFloat(val?val:'0')*parseFloat(this.state.val2)+''
      })
    } else if('val4' == type){
      this.setState({
        val4:val,
      })
    } else if('val5' == type){ //细粉 斤
      this.setState({
        val5:val,
        val6:parseFloat(val?val:'0')*parseFloat(this.state.val2)+''
      })
    } else if('val6' == type){ // 细粉 总金额
      this.setState({
        val6:val,
      })
    } else if('val7' == type){ //赠送
      this.setState({
        val7:val,
      })
    } else if('val8' == type){  //快递费
      this.setState({
        val8:val,
      })
    }
    setTimeout(()=>{
      this._countTotal();
    },10)
  }
  _countTotal(){
    var {val1,val2,val3,val5,val4,val6,val7,val8} = this.state;
    console.log(val4+','+val6)
    console.log(this.state)
    var totalFund = parseFloat(val4?val4:'0')+parseFloat(val6?val6:'0')+'';

    var totalWeight = parseFloat(val3?val3:'0') + parseFloat(val5?val5:'0') + parseFloat(val7?val7:'0');
    console.log('totalWeight',totalWeight);
    console.log('11',totalWeight*parseFloat(val1?val1:'0'));
    var totalCost = totalWeight*parseFloat(val1?val1:'0') + parseFloat(val8?val8:'0');
    console.log('55',totalCost)
    this.setState({
      totalFund : totalFund,
      totalCost : totalCost+'',
      totalIncome : parseFloat(totalFund)-parseFloat(totalCost),
    })
  }
  render(){
    return(
      <View style={styles.container}>
        <View style={[styles.row]}>
          <Text>日期</Text>
          <TouchableOpacity style={styles.flex1} onPress={()=>{this._selectDate()}}>
            <Text style={[styles.rightText]}>{this.state.time}</Text>
          </TouchableOpacity>
        </View>
        <Input title='成本（元/斤）' placeholder='请输入商品成本单价' 
          defaultValue="5" change={(val)=>{this._onchange(val,'val1')}}/>
        <Input title='单价（元/斤）' placeholder='请输入商品单价' 
          defaultValue="10" change={(val)=>{this._onchange(val,'val2')}}/>
        <Input title='售出宽粉（斤）' placeholder='请输入售出宽粉总重量' textStyle={{color:'#ED5100'}}
          val={this.state.val3}
          change={(val)=>{this._onchange(val,'val3')}}/>

        <Input title='售出宽粉总金额（元）' val={this.state.val4} 
          placeholder='自动计算宽粉总价' change={(val)=>{this._onchange(val,'val4')}}/>

        <Input title='售出细粉（斤）' val={this.state.val5} textStyle={{color:'#ED5100'}}
          placeholder='请输入售出细粉总重量' change={(val)=>{this._onchange(val,'val5')}}/>
        <Input title='售出细粉总金额（元）' val={this.state.val6} 
          placeholder='自动计算细粉总价' change={(val)=>{this._onchange(val,'val6')}}/>

        <Input title='赠送（斤）' placeholder='请输入赠送粉条的重量' val={this.state.val7}
          change={(val)=>{this._onchange(val,'val7')}}/>

        <Input title='快递费（元）' placeholder='请输入快递费用'  val={this.state.val8}
          change={(val)=>{this._onchange(val,'val8')}}/>
        <TextShow title="总收入" subTitle={this.state.totalFund}></TextShow>
        <TextShow title="总成本" subTitle={this.state.totalCost}></TextShow>
        <TextShow title="总收益" subTitle={this.state.totalIncome}></TextShow>
        <View style={styles.btnView}>
          <Button
            onPress={()=>this._save()}
            title="保存"
            color="#ED5100"
          />
        </View>
        <Toast ref="toast" position='bottom' positionValue={200} />
      </View>
    )
  }
}
class TextShow extends Component {
  render(){
    return(
      <View style={[styles.row,this.props.style]}>
        <Text>{this.props.title}</Text>
        <Text style={[styles.rightText,styles.flex1]}>{this.props.subTitle}元</Text>
      </View>
    )
  }
}
class Input extends Component{
  render(){
    return(
        <View style={[styles.inputRow,this.props.style]}>
          <Text style={[{fontSize:14,},this.props.textStyle]}>{this.props.title}</Text>
          <TextInput 
              placeholder={this.props.placeholder}
              defaultValue={this.props.defaultValue}
              style={styles.searchInput}
              underlineColorAndroid="transparent"
              onChangeText={this.props.change}
              value={this.props.val}
              placeholderTextColor='#A9A9A9'
              placeholderTextFont={14}
              keyboardType='numeric'
            />
        </View>
    )
  }
}
const styles = StyleSheet.create({
  btnView:{
    margin:10,
  },
  rightText:{
    color:'#A9A9A9',
    fontSize:14,
    textAlign:'center',
    fontWeight:'100',
  },
  flex1:{
    flex:1,
    fontSize:14,
    //borderWidth:1,
    //borderColor:'red'
  },
  row:{
    flexDirection:'row',
    alignItems:'center',
    marginLeft:20,
    marginRight:10,
    paddingTop:10,
    paddingBottom:10,
    borderBottomColor:'#ccc',
    borderBottomWidth:StyleSheet.hairlineWidth,
  },
  container:{
    flex:1,
  },
  inputRow:{
    flexDirection:'row',
    alignItems:'center',
    marginLeft:20,
    marginRight:10,
    borderBottomColor:'#ccc',
    borderBottomWidth:StyleSheet.hairlineWidth,
  },
  searchInput:{
    textAlign:'center',
    marginLeft:10,
    marginRight:14,
    padding:0,
    flex:1,
    height: 36, 
    color:'#A9A9A9',
  },

})